/**
 * 
 */
package ga.nqueens;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.jheuristics.Individual;
import org.jheuristics.ga.GAConfig;
import org.jheuristics.ga.GAStatus;
import org.jheuristics.ga.IndividualsFactory;
import org.jheuristics.ga.operators.Probability;
import org.jheuristics.ga.operators.reproductors.AbstractXOver;

/**
 * @author thiagoepdc
 *
 */
public class GoodNQueensCycleXOver extends AbstractXOver {


	/**
	 * @param probability
	 */
	public GoodNQueensCycleXOver(Probability probability) {
		super(probability, 0);
	}

	public Individual[] reproduce(Individual[] parents, GAStatus status, GAConfig config) {
		Individual[] result = super.reproduce(parents, status, config);
		if (result.length != 1) {
			return result[0].compareTo(result[1]) > 0 ? new Individual[] {result[0]} : new Individual[] {result[1]}; 
		}
		return result;
	}

	/* (non-Javadoc)
	 * @see org.jheuristics.ga.operators.reproductors.AbstractXOver#xover(org.jheuristics.ga.Individual[], org.jheuristics.ga.GAStatus, org.jheuristics.ga.GAConfig)
	 */
	protected Individual[] xover(Individual[] parents, GAStatus status, GAConfig config) {
		
	    if (!parents[0].equals(parents[1])) {
	        return doXOver(parents[0], parents[1], status, config);
	    }
	    return new Individual[] {parents[0], parents[1]};
	}

	/**
	 * TODO
	 *
	 * @param parent1
	 * @param parent2
	 * @param status
	 * @param config
	 * @return
	 */
	protected Individual[] doXOver(Individual parent1, Individual parent2, GAStatus status, GAConfig config) {
		return dox(parent1, parent2, config, config.getIndividualsFactory());
	}
	
	protected Individual[] dox(Individual parent1, Individual parent2, GAConfig config, IndividualsFactory factory) {
		
		List<Integer> gensParent1 = (List<Integer>) parent1.getGens();
		List<Integer> gensParent2 = (List<Integer>) parent2.getGens();
		
		List<Integer> gensParent2Removal = new LinkedList<Integer>(gensParent2);
		
		Board boardGensP1 = new Board(gensParent1);
		int[] hits = boardGensP1.hitsByQueen();
		
		int childGens [] = new int[gensParent1.size()];
		for (int i = 0; i < childGens.length; i++) {
			childGens[i] = -1;
		}

		for (int i = 0; i < gensParent1.size(); i++) {
			if(hits[i] == 0) {
				childGens[i] = gensParent1.get(i);
				gensParent2Removal.remove(gensParent1.get(i));
			}
		}
		
		for (Integer integer : gensParent2Removal) {
			
			for (int i = 0; i < gensParent1.size(); i++) {
				if(childGens[i] == -1) {
					childGens[i] = integer;
				}
			}
		}
		
		List<Integer> gens = new ArrayList<Integer>();
		for (int i = 0; i < childGens.length; i++) {
			gens.add(i, childGens[i]);
		}
		
		return new Individual[] {factory.createSpecificIndividual(gens, config)};
	}
	
	
}
